import {Component, OnInit, ViewChild, Input} from "@angular/core";
import "datatables";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ModalDirective} from "ng2-bootstrap/ng2-bootstrap";
import {CompanyChangeInfo} from "./company-change-info.class";
import {CompanyChangeService} from "./company-change.service";
import {DataTablesComponent, DataTablesComponentConfig} from "app/theme/components/dataTables";

@Component({
  selector: 'company-change',
  templateUrl: 'company-change.component.html',
  styleUrls: ['company-change.component.scss'],
  providers: [CompanyChangeService]
})
export class CompanyChangeComponent implements OnInit {
  @Input() type: string;
  @Input() applyTableUrl: string;
  @Input() applyUrl: string;
  @Input() applyInfoUrl: string;
  @Input() applyOutUrl: string;
  @Input() apprInfoUrl: string;
  @Input() updateInfoUrl: string;
  @Input() fileUploadUrl: string;

  @ViewChild('applyModal') applyModal: ModalDirective;
  @ViewChild('applyOutModal') applyOutModal: ModalDirective;
  @ViewChild('apprReviewModal') apprReviewModal: ModalDirective;
  @ViewChild('apprDeleteModal') apprDeleteModal: ModalDirective;
  @ViewChild('applyInModal') applyInModal: ModalDirective;
  @ViewChild('applyUpdateModal') applyUpdateModal: ModalDirective;

  @ViewChild(DataTablesComponent) dataTable: DataTablesComponent;

  private searchForm: CompanyChangeSearchForm = new CompanyChangeSearchForm();
  private applyForm: FormGroup;
  private applyOutForm: FormGroup;
  private applyInForm: FormGroup;
  private updateForm: FormGroup;

  private enterpriseInfoUrl = '/water/enterpriseinfo/findEnterprisesByName';
  private apprDownloadUrl = '/water/certificateSub/printModEnNameTab';
  private apprDownloadUserUrl = '/water/certificate/printRemoveApply';
  private apprDeleteUrl = '/water/certificate/delete';
  private applyInUrl = '/water/certificate/removeInEnterprise';
  private applyIndivUrl = '/water/certificate/individualRemoveIn';

  private disableUpload: boolean = false;
  private compChangeDoc: string = 'compChangeDoc';
  private issueCertificate: string = 'issueCertificate';
  private laborContract: string = 'laborContract';

  private sizeLimit = 2097152;

  private disableApplyBtn = true;
  private disableApplyOutBtn = true;
  private disableReviewBtn = true;
  private disableDownloadBtn = true;
  private disableDownloadUserBtn = true;
  private disableDeleteBtn = true;
  private disableApplyInBtn = true;
  private disableUpdateBtn = true;
  private applying = true;

  private downloadUrl: string = '';
  private downloadUserUrl: string = '';

  private selectedRowData: any = new CompanyChangeInfo();
  private applyDetailData: any = new CompanyChangeInfo();
  private applyInfo: any = {};
  private updateData: any = new CompanyChangeInfo();
  private updatePersonData: any = new CompanyChangeInfo();

  private _errorMsg: string;
  private errorShow = false;

  private applyModalDisplay = true;
  private updateModalDisplay = true;
  private applyInModalDisplay = true;

  private showComp = false;
  private dataTablesConfig: DataTablesComponentConfig = new DataTablesComponentConfig();

  constructor(private _fb: FormBuilder, private _service: CompanyChangeService) {
  }

  ngOnInit() {
    if (this.type === 'company') {
      this.buildApplyForm();
      this.buildUpdateForm();
    }
    if (this.type === 'user') {
      this.initSelect2();
    }
    this.buildApplyOutForm();
    this.buildApplyInForm();
    this.initDatatables();
  }


  buildApplyForm(): void {
    this.applyForm = this._fb.group(
      {
        'companyname': ['']
      }
    );

    this.applyForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

  buildApplyOutForm(): void {
    this.applyOutForm = this._fb.group(
      {
        'companyid': ['']
      }
    );

    this.applyOutForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

  buildApplyInForm(): void {
    this.applyInForm = this._fb.group(
      {
        'companyid': ['']
      }
    );

    this.applyInForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

  buildUpdateForm(): void {
    this.updateForm = this._fb.group(
      {
        'companyname': [this.updatePersonData.certificate.companynewname, [Validators.required]]
      }
    );

    this.updateForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }

  onValueChanged(data?: any) {
    // if (!this.applyForm) { return; }
    // const form = this.applyForm;
    // for (const field in this.formErrors) {

    //   this.formErrors[field] = '';
    //   const control = form.get(field);

    //   if (control && control.dirty && !control.valid) {
    //     const messages = this.validationMessages[field];
    //     for (const key in control.errors) {
    //       this.formErrors[field] += messages[key] + ' ';
    //     }
    //   }
    // }
  }

  private initDatatables() {
    this.dataTablesConfig.ajaxUrl = this.applyTableUrl;
    this.dataTablesConfig.selectable = 'single';
    this.dataTablesConfig.columnsDef = [
      {'name': '证书类型', 'id': 'type'},
      {'name': '证书编号', 'id': 'serialno'},
      {'name': '姓名', 'id': 'name'},
      {'name': '原公司名', 'id': 'companyoldname'},
      {'name': '新公司名', 'id': 'companynewname'},
      {'name': '签发日期', 'id': 'issuedate'},
      {'name': '有效期', 'id': 'availabletime'},
      {'name': '提交时间', 'id': 'submittime', 'orderable': true},
      {'name': '审批时间', 'id': 'verifytime', 'orderable': true},
      {'name': '状态', 'id': 'verified'}
    ];
  }

  private initSelect2() {
    let data: any = [];
    this._service.getEnterpriseInfo(this.enterpriseInfoUrl).then(res => {
      let enterprises = res.data;
      for (let i = 0; i < enterprises.length; i++) {
        let item: any = {};
        item.id = enterprises[i].ids;
        item.text = enterprises[i].name;
        data.push(item);
      }
      data.push("个人");
      jQuery('#companyid').select2({
        data: data
      });

      jQuery('#companyname').select2({
        data: data
      });
    });
  }

  public onSubmit(action: string): void {
    // let compChangeInfo: any;
    // if (this.type === 'user') {
    //   let enterId: any = document.getElementById('companyid');
    //   compChangeInfo.companyid = enterId.value;
    // }
    this.applyInfo.ids = this.selectedRowData[0].ids;
    this.applyInfo.companyname = this.applyForm.value.companyname;

    this.applyInfo.action = action;

    this._service.submit(this.applyUrl, this.applyInfo)
      .then(res => {
        if (res.status === "success") {
          this.apprApplyClose();
          this.dataTable.draw(false);
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  // private loadComChangeForm(ids: string) {
  //   this.clearCertInfo();
  //   this._renewService.loadRenewInfo(this._compChaInfoUrl, ids)
  //     .then(res => {
  //       if (res.status === "success") {
  //         this.companyChangeInfo = res.data[0];
  //         this.companyChangeModal.show();
  //         this.buildForm();
  //       } else {
  //
  //       }
  //     });
  // }

  update() {
    this.applying = false;
    this.updateModalDisplay = true;
    this.updateData = new CompanyChangeInfo();
    this.updateData.pkid = this.selectedRowData[0].pkid;
    this.loadUpdateInfo(this.updateData.pkid);
  }

  private loadUpdateInfo(pkid: string) {
    this.updatePersonData = new CompanyChangeInfo();
    this._service.updateAppr(this.apprInfoUrl, pkid)
      .then(res => {
        if (res.status === 'success') {
          this.updatePersonData = res.data;
          this.buildUpdateForm();
          this.applyUpdateModal.show();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  updateApply(action:string){
    let updatedata = this.updateForm.value;
    this.updateData.companyname = updatedata.companyname;
    this.updateData.action = action;
    this.updateData.pkid = this.selectedRowData[0].pkid;

    this._service.submitUpdate(this.updateInfoUrl, this.updateData)
      .then(res => {
        if (res.status === "success") {
          this.applyUpdateClose();
          this.dataTable.draw();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  review() {
    let data = this.verifyStatus();
    this.loadInfo(data.id, data.url, this.selectedRowData[0].verified, this.apprReviewModal);
  }

  verifyStatus() {
    let id;
    let url;
    if (this.selectedRowData[0].verified === '可申请') {
      id = this.selectedRowData[0].ids;
      url = this.applyInfoUrl;
    } else {
      id = this.selectedRowData[0].pkid;
      url = this.apprInfoUrl;
    }

    return {id: id, url: url};
  }

  private loadInfo(id: string, url: string, status: string, apprModal: ModalDirective) {
    this.applyDetailData = new CompanyChangeInfo();
    this._service.reviewAppr(url, id, status)
      .then(res => {
        if (res.status === 'success') {
          this.applyDetailData = res.data;
          apprModal.show();
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  handleError(e:any){
    if(e.type == 'error'){
      this.errorShow = true;
    }
  }

  private addApply(): void {
    this.applyModalDisplay = true;
    let data = this.verifyStatus();
    this.applying = true;
    this.loadInfo(data.id, data.url, this.selectedRowData[0].verified, this.applyModal);
  }

  private addApplyOut(): void {
    this.applyOutModal.show();
  }

  private addApplyIn(): void {
    this.applyInModalDisplay = true;
    this.initSelect2();
    this.applyInModal.show();
  }

  search() {
    this.dataTable.draw();
  }

  showDeleteModal() {
    this.apprDeleteModal.show();
  }

  onHideModal(): void {
    this.clearModal();
    jQuery(".modal-backdrop").remove();
  }

  clearModal(){
    this._errorMsg = null;
    this.applyModalDisplay = false;
    this.updateModalDisplay = false;
    this.applyInModalDisplay = false;
  }

  updateDateRange(event) {
    this.searchForm.startdate = this.date2String(event.beginDate);
    this.searchForm.enddate = this.date2String(event.endDate);
  }

  private date2String(date: any): string {
    if (Object.keys(date).length === 0 || date === null || date === undefined || (date.year == 0 && date.month == 0 && date.day == 0)) {
      return null;
    }

    let str = date.year + '-';
    if (date.month < 10) {
      str += '0';
    }
    str += date.month + '-';

    if (date.day < 10) {
      str += '0';
    }
    str += date.day;
    return str;
  }

  public applyIn(): void {
    this._saveAppr(this.applyInModal);
  }

  public applyOut(comment: string) {
    this.applyInfo.ids = this.selectedRowData[0].ids;

    this.applyInfo.reason = comment;
    let enterId: any = document.getElementById('companyname');
    let index = enterId.selectedIndex;
    this.applyInfo.companyname = enterId.options[index].text;
    this.applyInfo.companyid = enterId.options[index].value;

    this._service.submitAppr(this.applyOutUrl, this.applyInfo).then(result => {
      if (result.status === 'success') {
        this.applyOutModal.hide();
        this.dataTable.draw(false);
      } else {
        this._errorMsg = result.data;
      }
    }, error => {
      this._errorMsg = error;
    });
  }


  private _saveAppr(modal: ModalDirective) {
    let url = '';

    this.applyInfo.reason = 'qq';
    if (this.showComp === true) {
      this.applyInfo.ids = this.selectedRowData[0].ids;
      let enterId: any = document.getElementById('companyid');
      let index = enterId.selectedIndex;
      // this.applyInfo.companyname = enterId.options[index].text;
      if(index<0){
        index = 0;
      }
      this.applyInfo.companyid = enterId.options[index].value;
      url = this.applyIndivUrl;
    }else{
      this.applyInfo.pkid = this.selectedRowData[0].pkid;
      url = this.applyInUrl;
    }

    this._service.submitAppr(url, this.applyInfo).then(result => {
      if (result.status === 'success') {
        modal.hide();
        this.dataTable.draw(false);
      } else {
        this._errorMsg = result.data;
      }
    }, error => {
      this._errorMsg = error;
    });
  }


  public delete(): void {
    let pkids = [];
    for (let row of this.selectedRowData) {
      pkids.push(row.pkid);
    }
    this._service.deleteAppr(this.apprDeleteUrl, pkids)
      .then(res => {
        if (res.status === 'success') {
          this.apprDeleteModal.hide();
          this.dataTable.draw(false);
          this.disableDeleteBtn = true;
        } else {
          this._errorMsg = res.data ? res.data : '网络错误';
        }
      }, error => {
        this._errorMsg = error;
      });
  }

  public apprDeleteClose() {
    this._errorMsg = null;
    this.apprDeleteModal.hide();
  }

  public apprApplyClose(){
    this._errorMsg = null;
    this.applyModalDisplay = false;
    this.applyModal.hide()
  }

  public applyUpdateClose(){
    this._errorMsg = null;
    this.updateModalDisplay = false;
    this.applyUpdateModal.hide()
  }

  public applyInClose(){
    this._errorMsg = null;
    this.applyInModalDisplay = false;
    this.applyModal.hide();
  }


  onFileUploading() {
    this.disableUpload = true;
  }

  onFinishUploading(replyObj: any) {
    this.applyInfo[replyObj.property] = replyObj.rsp.data[0].ids;
    this.disableUpload = false;
  }

  onFinishUploadingUpdate(replyObj: any) {
    this.updateData[replyObj.property] = replyObj.rsp.data[0].ids;
    this.disableUpload = false;
  }

  private disableAllButtons() {
    this.disableReviewBtn = this.disableApplyOutBtn = this.disableApplyBtn = this.disableApplyInBtn = this.disableDeleteBtn = true;
  }

  tableRowSelect(rowData: any[]) {
    this.disableAllButtons();
    this.disableReviewBtn = rowData.length !== 1;
    if (rowData.length === 1 && rowData[0].verified === '可申请') {
      this.disableApplyBtn = false;
      if(rowData[0].companyoldname != '个人'){
        this.disableApplyOutBtn = false;
      }else{
        this.disableApplyOutBtn = true;
      }
      // this.selectedRowData = rowData[0];
    }
    this.disableUpdateBtn = rowData.length !== 1 || rowData[0].verified !== '未提交';
    this.disableDownloadBtn = rowData.length !== 1 || rowData[0].verified !== '待审核';
    this.disableApplyInBtn = (rowData.length !== 1 || rowData[0].verified !== '已调出') && (rowData[0].companyoldname !== '个人' || rowData[0].verified !== '可申请');

    if ((rowData[0].companyoldname === '个人' && rowData[0].verified != '已调出')||(rowData[0].companynewname === '个人' && rowData[0].verified == '已调出')) {
      this.showComp = true;
      this.initSelect2();
    }else{
      this.showComp = false;
    }

    if (!this.disableDownloadBtn) {
      this.downloadUrl = this.apprDownloadUrl + '?ids=' + rowData[0].ids;
    }
    this.disableDownloadUserBtn =(rowData.length !== 1 || rowData[0].verified != '待调出') && (rowData.length !== 1||rowData[0].verified != '待调入');
    if (!this.disableDownloadUserBtn) {
      this.downloadUserUrl = this.apprDownloadUserUrl + '?ids=' + rowData[0].ids + '&verifytype=' + rowData[0].verified;
    }
    if(this.type === 'company'){
      this.disableDeleteBtn = !(rowData.length === 1 && rowData[0].verified === '未通过');
    }else if(this.type === 'user'){
      this.disableDeleteBtn = (rowData.length !== 1 || rowData[0].verified != '调出失败') && (rowData.length !== 1||rowData[0].verified != '调入失败');
    }
    this.selectedRowData = rowData;
  }
}

export class CompanyChangeSearchForm {
  public idcard: string = '';
  public name: string = '';
  public type: string = '';
  public verified: string = '可申请';
  public enddate: string = '';
  public startdate: string = '';
}
